package com.zzx.controller;

import com.zzx.domain.Role;
import com.zzx.domain.Vo.AddRoleVo;
import com.zzx.domain.tv.RolePerimession;
import com.zzx.exception.ExceptionState;
import com.zzx.exception.SystemException;
import com.zzx.service.RoleService;
import com.zzx.util.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@RestController
public class RoleController {

    @Autowired
    private RoleService roleService;

    /**
     * 获取全部角色及其所有的权限
     * @return
     */
    @PreAuthorize("hasAuthority('角色列表')")
    @GetMapping("/roles")
    public ResponseResult RoleList(){
        return roleService.RoleList();
    }

    /**
     * 添加角色
     * @param role
     * @return
     */
    @PreAuthorize("hasAuthority('添加角色')")
    @PostMapping("/roles")
    public ResponseResult addRole(@RequestBody Role role){
        if(role.getRoleName().trim().length()==0)throw new SystemException(ExceptionState.UNROLENAME);
        return roleService.addRole(role);
    }

    /**
     * 根据id查询角色
     * @param id
     * @return
     */
    @PreAuthorize("hasAuthority('获取角色详情')")
    @GetMapping("/roles/{id}")
    public ResponseResult selectRoleById(@PathVariable("id")Integer id){
        return roleService.selectRoleById(id);
    }

    /**
     * 根据id更新角色信息
     * @param id
     * @param addRoleVo
     * @return
     */
    @PreAuthorize("hasAuthority('更新角色信息')")
    @PutMapping("/roles/{id}")
    public ResponseResult updateRoleById(@PathVariable Integer id,@RequestBody AddRoleVo addRoleVo){
        return roleService.updateRoleById(id,addRoleVo);
    }

    /**
     * 根据id删除角色
     * @param id
     * @return
     */
    @PreAuthorize("hasAuthority('删除角色')")
    @DeleteMapping("/roles/{id}")
    public ResponseResult deleteRoleById(@PathVariable("id")Integer id){
        return roleService.deleteRoleById(id);
    }

    /**
     * 角色授权
     * @return
     */
    @PreAuthorize("hasAuthority('角色授权')")
    @PostMapping("/roles/{roleId}/rights")
    public ResponseResult setPermission(@PathVariable("roleId") Integer roleId, @RequestBody RolePerimession rolePerimession){
        return roleService.setPermission(roleId,rolePerimession.getRids());
    }

    /**
     * 删除角色的指定权限
     * @param roleId 角色id
     * @param rightId 权限id
     * @return
     */
    @PreAuthorize("hasAuthority('更新角色权限')")
    @DeleteMapping("/roles/{roleId}/rights/{rightId}")
    public ResponseResult deleteByPermission(@PathVariable("roleId") Integer roleId,@PathVariable("rightId") Integer rightId){
        return roleService.deleteByPermission(roleId,rightId);
    }

}
